//
//  BSTool.m
//  PhotographyStudi
//
//  Created by 叶一枫 on 2017/5/16.
//  Copyright © 2017年 叶一枫. All rights reserved.
//

#import "BSTool.h"

@interface BSTool()<UITextFieldDelegate>

@property(nonatomic,strong)UIButton *tipButton;

@end

@implementation BSTool

//单例  方便调用方法
+ (BSTool *)sharedBSTool
{
    static BSTool *shareBSTool = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        shareBSTool = [[self alloc] init];
    });
    return shareBSTool;
}

//调整图片大小，重新绘制图片，可能造成清晰度降低的问题

-(UIImage*)scaleImageToSize:(UIImage*)img size:(CGSize)size{
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


- (void)authenticateUserFromModel:(NSString*)modeStr complet:(ToolBlock)complet{
    //初始化上下文对象
    LAContext* context = [[LAContext alloc] init];
    //错误对象
    NSError* error = nil;
    NSString* result = @"通过Home键验证指纹识别身份";
    
    //首先使用canEvaluatePolicy 判断设备是否支持指纹
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        //支持指纹验证
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
            
            if (success) {
                complet(1,nil);
            }else{
                complet(error.code==1?0:error.code,nil);
            }
        }];
    }else{
        //不支持指纹识别功能
        [[BSTool sharedBSTool]goRootVCFromtype:@"LOGIN"];
    }
}

-(void)goRootVCFromtype:(NSString *)type{
    /*
     HOME               :   首页
     LOGIN              :   登录页
     
     */
    
    if (![type isEqualToString:@"LOGIN"]) {
        BaseNavigationController *navi = (BaseNavigationController*)[self getVCFromStoryboardWithID:@"BaseNavigationController"];
        UIApplication *appdelegate = [UIApplication sharedApplication];
        appdelegate.delegate.window.rootViewController = navi;
    }else{
        LoginViewController *loginVC = (LoginViewController*)[self getVCFromStoryboardWithID:@"LoginViewController"];
        UIApplication *appdelegate = [UIApplication sharedApplication];
        appdelegate.delegate.window.rootViewController = loginVC;
        
    }
}

-(UIViewController*)getVCFromStoryboardWithID:(NSString *)identifier{
    
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *viewController = [storyBoard instantiateViewControllerWithIdentifier:identifier];
    return viewController;
}


/**
 根据文字获取内容高度或宽度
 
 @param str 计算的字符串
 @param size 宽或高的固定大小
 @param font label字体
 @param getHeight 是否是计算高度
 @return size
 */
-(CGSize)getSizeWithStr:(NSString *)str size:(CGFloat)size font:(UIFont *)font height:(BOOL)getHeight{
    
    CGSize lableSize;
    lableSize = [str boundingRectWithSize:CGSizeMake(getHeight?size:MAXFLOAT, getHeight?MAXFLOAT:size) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
    
    return lableSize;
}


-(void)alertBaseWithTitle:(NSString *)title des:(NSString *)des complet:(ToolBlock)complet{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:des preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:0 handler:^(UIAlertAction * _Nonnull action) {
        complet(1,nil);
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction * _Nonnull action) {
        complet(0,nil);
    }];
    
    [alertController addAction:sure];
    [alertController addAction:cancel];
    
    
    [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
}


-(void)alertWithTitle:(NSString *)title des:(NSString *)des actions:(NSArray *)actionArr{
    
    //改变alertController的message字体
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:des];
    [alertControllerStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, des.length)];
    [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, des.length)];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:des preferredStyle:actionArr.count>1?0:1];
    
    //改变alertController的message字体
    [alertController setValue:alertControllerStr forKey:@"attributedMessage"];
    
    for (UIAlertAction*action in actionArr) {
        [alertController addAction:action];
    }
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:cancel];
    
    [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
}


-(void)alertTextFiledTitle:(NSString*)title des:(NSString*)des complet:(ToolBlock)complet number:(BOOL)isNumber{
    
    //修改title
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:des];
    [alertControllerStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, des.length)];
    
    [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, des.length)];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:des preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController setValue:alertControllerStr forKey:@"attributedMessage"];
    
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * textField){
        if (isNumber) {
            textField.placeholder = @"只支持输入数字";
            textField.delegate = self;
        }
        textField.clearButtonMode = UITextFieldViewModeAlways;
    }];
    
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:0 handler:^(UIAlertAction * _Nonnull action) {
        complet(1,alertController.textFields.firstObject);
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction * _Nonnull action) {
        complet(0,nil);
    }];
    
    [alertController addAction:sure];
    [alertController addAction:cancel];
    
    [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    return [[BSTool sharedBSTool] validateNumber:string];
}

-(void)alertImagePickerWithTitle:(NSString*)title des:(NSString*)des complet:(ToolBlock)complet{
    
    //修改title
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:des];
    [alertControllerStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, des.length)];
    
    [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(0, des.length)];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:des preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alertController setValue:alertControllerStr forKey:@"attributedMessage"];
    
    UIAlertAction *takePhoto = [UIAlertAction actionWithTitle:@"拍照" style:0 handler:^(UIAlertAction * _Nonnull action) {
        complet(1,nil);
    }];
    
    UIAlertAction *photoLibrary = [UIAlertAction actionWithTitle:@"相册" style:0 handler:^(UIAlertAction * _Nonnull action) {
        complet(2,nil);
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction * _Nonnull action) {
        complet(0,nil);
    }];
    
    [alertController addAction:photoLibrary];
    [alertController addAction:takePhoto];
    [alertController addAction:cancel];
    
    [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
}

-(UIViewController *)getCurrentVC{
    
    UIViewController* viewController = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        viewController = nextResponder;
    else
        viewController = window.rootViewController;
    
    return viewController;
}

-(UIImage *)imageFromText:(NSString*)content withFont:(CGFloat)fontSize withTextColor:(UIColor *)textColor withBgColor:(UIColor *)bgColor withImageBounds:(CGRect)bounds{
    
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.alignment = NSTextAlignmentCenter;
    
    NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:textColor,NSParagraphStyleAttributeName : paragraph };
    
    CGRect rect = [content boundingRectWithSize:CGSizeMake(0, bounds.size.width) options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:attribute context:nil];
    
    UIGraphicsBeginImageContextWithOptions(rect.size,NO,UIScreen.mainScreen.scale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [bgColor set];
    UIRectFill(CGRectMake(0, 0, rect.size.width, rect.size.height));
    
    CGContextSetCharacterSpacing(ctx, 10);
    CGContextSetTextDrawingMode (ctx, kCGTextFill);
    [textColor set];
    [content drawInRect:rect withAttributes:attribute];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
    
}

//指定上部圆角 下边直角
-(void)setWidgetLayer:(UIView*)view withCorneradid:(UIRectCorner)corner withCorneradii:(CGSize)size{
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:corner cornerRadii:size];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.fillColor = [UIColor colorWithHexString:@"f0f1f2"].CGColor;
    shapeLayer.lineJoin = kCALineJoinRound;
    shapeLayer.lineCap = kCALineCapRound;
    shapeLayer.path = path.CGPath;
    [view.layer addSublayer:shapeLayer];
    view.layer.masksToBounds = YES;
}

- (BOOL)isChineseWithStr:(NSString *)str
{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:str];
}

- (BOOL)includeChineseWithStr:(NSString *)str
{
    for(int i=0; i< [str length];i++)
    {
        int a =[str characterAtIndex:i];
        if( a >0x4e00&& a <0x9fff){
            return YES;
        }
    }
    return NO;
}


- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

-(BOOL)isValidUrl:(NSString *)str{
    
    NSString *regex =@"[a-zA-z]+://[^\\s]*";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [urlTest evaluateWithObject:str];
}

-(void)showTip:(NSString *)alertStr timerInterval:(NSTimeInterval)timerInterval{
    
    //点击按钮
    UIButton *tipButton = [[UIButton alloc]initWithFrame:CGRectMake(0, -100, VIEW_W, 100)];
    tipButton.backgroundColor = [UIColor whiteColor];
    
    //提示文字
    NSString *tipStr = [NSString stringWithFormat:@"ⓘ  %@",alertStr];
    UILabel *tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, tipButton.height - 44, VIEW_W - 40, 44)];
    tipLabel.font = [UIFont boldSystemFontOfSize:16];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:tipStr];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 1)];
    tipLabel.attributedText = str;
    [tipButton addSubview:tipLabel];
    
    //加到Window上
    AppDelegate *delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [delegate.window addSubview:tipButton];
    //弹簧动画效果
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.35 initialSpringVelocity:0.1 options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
        
        [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
        tipButton.frame = CGRectMake(0, -36, VIEW_W, 100);
        
    }completion:^(BOOL finished) {
        
        [UIView animateWithDuration:0.5 delay:timerInterval options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            tipButton.frame = CGRectMake(0, -100, VIEW_W, 100);
            tipButton.alpha = 0;
            
        } completion:^(BOOL finished) {
            tipButton.alpha = 1;
        }];
    }];
}


-(BOOL)validStr:(NSString *)str{
    
    NSString *validStr = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@.";
    
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:validStr] invertedSet];
    NSString *filtered = [[str componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [str isEqualToString:filtered];
}

-(id)userDefaultValueforkey:(NSString *)key{
    
    return [[NSUserDefaults standardUserDefaults]objectForKey:key];
}

-(void)userDefaultKey:(NSString *)key forValue:(id)value{

    [[NSUserDefaults standardUserDefaults]setObject:value forKey:key];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

//将文字转化为拼音
- (NSString *)transformToPinyin:(NSString *)textStr{
    //例如：苦海无涯适应工作室
    //将汉字转化为字母（带有声调）、英文数字不变
    NSMutableString *mutbleStr = [NSMutableString stringWithString:textStr];
    CFStringTransform((CFMutableStringRef)mutbleStr,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)mutbleStr,NULL, kCFStringTransformStripDiacritics,NO);
    //转化拼音后，用空格分成数组。péng chéng wàn lǐ shè yǐng gōng zuò shì
    NSArray *pinyinArray = [mutbleStr componentsSeparatedByString:@" "];
    NSMutableString *myString = [NSMutableString string];
    
    int count = 0;
    
    //得到全拼字符串（kuhaiwuya...,haiwuya...,wuya...）
    for (int  i = 0; i < pinyinArray.count; i++){
        
        for(int i = 0; i < pinyinArray.count;i++){
            if (i == count) {
                [myString appendString:@"$"];//区分第几个字母
            }
            [myString appendFormat:@"%@",pinyinArray[i]];
        }
        [myString appendString:@","];
        count ++;
    }
    //得到首字母拼写（khwysygzs,hwysygzs,wysygzs,....）
    NSMutableString *firstStr = [NSMutableString new];
    for (NSString *str in pinyinArray){
        if (str.length > 0){
            [firstStr appendString:[str substringToIndex:1]];
        }
    }
    
    //最后将字符和首字母拼接到一起
    [myString appendFormat:@"$%@",firstStr];
    [myString appendFormat:@",$%@",textStr];
    
    return myString;
}



@end
